﻿
var type = "";
var typeName = "";
var cityId = "";
var $table = $('#table');
var $tree = $('#tree');

var regEx = new RegExp("\\-", "gi");

///////////////////////////////////////////////////////////////////////////////
//日历操作
///////////////////////////////////////////////////////////////////////////////
//function addDate(date, days) {
//    var d = new Date(date);
//    d.setDate(d.getDate() + days);
//    var month = d.getMonth() + 1;
//    var day = d.getDate();
//    if (month < 10) {
//        month = "0" + month;
//    }
//    if (day < 10) {
//        day = "0" + day;
//    }
//    var val = d.getFullYear() + "" + month + "" + day;
//    return val;
//}
function comptime(beginTime, endTime) {
    //var beginTime = "2009-09-21 00:00:00";
    //var endTime = "2009-09-21 00:00:01";
    console.log(beginTime + "|||" + endTime);
    var beginTimes = beginTime.substring(0, 10).split('-');
    var endTimes = endTime.substring(0, 10).split('-');

    beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
    endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);

    //alert(beginTime + "aaa" + endTime);
    //alert(Date.parse(endTime));
    //alert(Date.parse(beginTime));
    var a = (Date.parse(endTime) - Date.parse(beginTime));// / 3600 / 1000;
    if (a < 0) {
        //alert("endTime小!");
        return -1;
    } else if (a > 0) {
        //alert("endTime大!");
        return 1;
    } else if (a == 0) {
        //alert("时间相等!");
        return 0;
    } else {
        return 'exception'
    }
}
$(function () {
    console.log(isAuthority('293'));
    if (isAuthority('293')) {
        $('#edit_item').attr('style', "display:block;");
    }
    initTree();
    initTable();

});

function init() {
    var divs = document.getElementsByTagName("div");
    for (i = 0; i < divs.length; i++) {
        divs[i].style.backgroundColor = getRandomColor();
    }

}

function getRandomColor() {
    return '#' + (function (color) {

        return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)])
         && (color.length == 6) ? color : arguments.callee(color);

    })('');
}

//初始化td
var initializeTd = function ($td, tdText, PaiBanCalendar) {
    $td.empty();
    //alert(tdText);
    //日期
    var $weekSpan = $("<span></span>").appendTo($td);
    $weekSpan.text(tdText);

    //是否 小于等于今天
    if (PaiBanCalendar.pB_IsBeforeToday == 1) {
        $td.css("background-color", "#f5f3f3");
    }

    //冲突
    if (PaiBanCalendar.pB_ChongTu == 1) {
        var $ctDiv = $("<div></div>").appendTo($td);
        $ctDiv.addClass("ct-td-div");
        $ctDiv.text("数据冲突");
        $("<br />").appendTo($ctDiv);
        var $ctA = $("<a></a>").appendTo($ctDiv);
        $ctA.text("点击查看");
        $ctA.click(function () {
            alert("查看详情");
        });
    }
    else {
        var detailContent = "<div class='detail-span-content'>";
        //console.log(PaiBanCalendar.pB_BanZu.pZ_Id + "/????");

        //班组div
        if (PaiBanCalendar.pB_BanZu.pZ_Id != 0) {
            //var $bzDiv = $("<div></div>").appendTo($td);
            //$bzDiv.addClass("bz-td-div");
            //$bzDiv.css("background-color", "red");
            //detailContent += "班组：" + PaiBanCalendar.pB_BanZu.bZ_Name;

            //console.log(PaiBanCalendar.pB_BanCi.bC_WorkTimeL)
            //添加班次Id
            //PaiBanCalendar.pB_BanCi.bC_WorkTimeL
            var arr = [];
            //$.each(PaiBanCalendar.pB_BanCi.bC_WorkTimeL, function (ii, val) {
            //    //$red += "," + $(this).wT_Id;
            //    arr.push($(this).wT_Id);
            //});

            //$td.attr("redstate", $red);
            $td.attr("bcId", PaiBanCalendar.pB_BanZu.pZ_Id);
            var $bcDiv = $("<div></div>").appendTo($td);
            $bcDiv.addClass("bc-td-div");


            //$bcDiv.css("background-color", "red");
            //detailContent += "<br />班次：" + PaiBanCalendar.pB_BanZu.bZ_Name;
            //时间段
            for (var x = 0; x < PaiBanCalendar.pB_BanCi.bC_WorkTimeL.length; x++) {
                var $bC_WorkTimeL = PaiBanCalendar.pB_BanCi.bC_WorkTimeL[x];
                var $bcItem = $("<div></div>").appendTo($bcDiv);
                $bcItem.addClass("bz-td-div2");
                $bcItem.attr("id", $bC_WorkTimeL.wT_Id);
                $bcItem.text($bC_WorkTimeL.wT_BeginTime);
                arr.push($bC_WorkTimeL.wT_Id);
                if (x > 3) {
                    $bcItem.hide();
                }

                detailContent += "</br>" + PaiBanCalendar.pB_BanCi.bC_WorkTimeL[x].wT_BeginTime +
                    //" ~ " + PaiBanCalendar.pB_BanCi.bC_WorkTimeL[x].wT_EndTime +
                    "";
            }
            //console.log(arr.join(','));
            if (arr.length > 0) {
                $td.attr("redstate", arr.join(','));
            }
        }

        //班次div
        if (PaiBanCalendar.pB_BanCi.bC_Id != 0) {
            //添加班次Id
            $td.attr("bcId", PaiBanCalendar.pB_BanCi.bC_Id);
            var $bcDiv = $("<div></div>").appendTo($td);
            $bcDiv.addClass("bc-td-div");
            $bcDiv.css("background-color", PaiBanCalendar.pB_BanCi.bC_Color);
            detailContent += "<br />班次：" + PaiBanCalendar.pB_BanCi.bC_Name;
            //时间段
            for (var x = 0; x < PaiBanCalendar.pB_BanCi.BC_WorkTimeL.length; x++) {
                detailContent += "</br>(" + PaiBanCalendar.pB_BanCi.BC_WorkTimeL[x].WT_BeginTime + " ~ "
                    + PaiBanCalendar.pB_BanCi.BC_WorkTimeL[x].WT_EndTime + ")";
            }
        }

        //请假div
        if (PaiBanCalendar.pB_Leave.LD_Id != 0) {
            var $ldDiv = $("<div></div>").appendTo($td);
            $ldDiv.addClass("ld-td-div");
            $ldDiv.text(PaiBanCalendar.pB_Leave.lD_TypeName);
            //添加到详细
            //detailContent += "<hr />" + PaiBanCalendar.pB_Leave.lD_TypeName + "：" + PaiBanCalendar.pB_Leave.lD_PassStr;
        }

        //出差div
        if (PaiBanCalendar.pB_Trip.tD_Id != 0) {
            var $tdDiv = $("<div></div>").appendTo($td);
            $tdDiv.addClass("td-td-div");
            $tdDiv.text(PaiBanCalendar.pB_Trip.tD_Name);
            //添加到详细
            //detailContent += "<hr />" + PaiBanCalendar.pB_Trip.tD_Name + "：" + PaiBanCalendar.pB_Trip.TD_PassStr;
        }

        //加班div
        if (PaiBanCalendar.pB_IsOverTime == 1) {
            var $odDiv = $("<div></div>").appendTo($td);
            $odDiv.addClass("od-td-div");
            $odDiv.text("加班");
            //添加到详细
            detailContent += "<hr />加班：整天";
        }

        //详细页面
        if (PaiBanCalendar.pB_BanCi.bC_Id != 0 || PaiBanCalendar.pB_BanZu.pZ_Id != 0) {
            var $detailSpan = $("<span></span>").appendTo($td);
            $detailSpan.addClass("detail-span");
            $detailSpan.addClass("popover-options");

            //console.log(detailContent);
            if (PaiBanCalendar.pB_BanCi.bC_WorkTimeL.length > 4) {
                var $detailA = $("<a href='javascript:' type='button' title='详细' data-container='body' data-toggle='popover' data-trigger='hover'>详细</a>").appendTo($detailSpan);
                $detailA.attr("data-content", detailContent + "</div>");
                $(".popover-options a").popover({ html: true });
            }

        }

        $td.hover(function () {
            $(this).find(".popover-options").show();
        }, function () {
            $(this).find(".popover-options").hide();
        })
    }

    //添加td事件
    $td.removeAttr('onclick').unbind('click').click(function () {
        //console.log($(this).attr("Id") + "--" + laydate.now(0, "YYYY-MM-DD"));



        //获取所选人员
        var table = $(this);
        var $td = $(this).find('.bc-td-div');
        var selectedArr = $tree.jstree("get_selected");
        var selectedMems = "";
        $.each(selectedArr, function (index, value) {
            selectedMems += "," + value;
        })

        //根据日期字符串转换成日期 
        var _date = $(table).attr("id").substr(3);
        var milliseconds = Date.parse(_date.replace(regEx, "/"));
        var _tdDate = new Date();
        _tdDate.setTime(milliseconds);


        if ($("#redNum").html() == 1) {
            if (selectedMems.length <= 0) {
                //alert("请选择需要排班的人员");
                parent.layer.alert('请选择需要排班的人员')
            } else if (new Date() >= _tdDate) {
                //alert("过去的日期不能进行排班");
                parent.layer.alert('过去的日期不能进行排班')
            }
            else {

                if (selectedArr.contains("-1")) {
                    selectedArr.removeObj("-1");
                }
                if (selectedArr.length > 4) {
                    parent.layer.alert('值班人员，最多4个'); return;
                }

                if ($(table).attr("redstate") == undefined || $(table).attr("redstate") == 0) {

                    $.each(selectedArr, function (index, value) {

                        var $attr_txt = $('#' + value + '_anchor').text();
                        var $item_u = $('<div class="bz-td-div2" val="' + value + '"></div>').appendTo($td);
                        $item_u.text($attr_txt);
                    })
                    $(table).attr("redstate", selectedArr);

                } else {
                    parent.layer.alert('请取消原有的排班')
                }

            }
        }
        if ($("#redNum").html() == 2) {
            $("#" + $(this).attr("Id")).css({ "backgroundColor": "green" });
            $("#" + $(this).attr("Id")).attr("redstate", "2");
        }
        console.log($(this).attr("Id").substr(3));
        if ($("#redNum").html() == 0) {//new Date(jsonDate.substring(0, 10))
            if (comptime((new Date().Format("yyyy-MM-dd")), ($(this).attr("Id").substr(3))) < 0) {
                parent.layer.alert('过去的日期不能进行修改');
                return;
            }
            $($td).html("");
            $(table).attr("redstate", 0);
            //$(table).removeAttr("redstate");

            //$("#" + $(this).attr("Id")).css({ "backgroundColor": "white" });
            //$("#" + $(this).attr("Id")).attr("redstate", "0");
        }

    })

    ////添加td事件
    //$td.removeAttr('onclick').unbind('click').click(function () {
    //    console.log($(this).attr("Id"));
    //    var $eventDiv = $("#eventDiv");

    //    switch ($eventDiv.attr("bType")) {
    //        case "bc":
    //            if ($(this).attr("bcId") && $td.attr("bcId") > 0) {
    //                var r = confirm("将要被修改的日期已有班次，您确认要覆盖吗？");
    //                if (r == true) {
    //                    updateBanCi($(this));
    //                }
    //            }
    //            else {
    //                updateBanCi($(this));
    //            }
    //            break;
    //        case "bz":
    //            var r = confirm("选择日期后的排班将会被覆盖，您确认添加该班组序列吗？");
    //            if (r == true) {
    //                updateBanZu($(this));
    //            }
    //            break;
    //        case "none":
    //            break;
    //    }
    //})
}

//查询的参数
var queryParams = function (params) {
    var temp = {
        pageSize: params.limit,                             //行数
        pageIndex: (params.offset / params.limit) + 1,      //页码
        id: type,
        search: $('#searchKey').val()                       //查询内容
    };
    return temp;
};
function initTable() {
    $table.bootstrapTable({
        url: '/Item/IndexAsync',            //数据来源地址
        method: 'post',                     //数据请求方式
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否启用分页
        sidePagination: 'server',           //在服务器端分页
        queryParams: queryParams,           //传递参数
        pageNumber: 1,                      //初始化加载第一页，默认第一页
        pageSize: 20,                       //每页的记录行数（*）
        pageList: [10, 20, 30, 40, 50],     //可供选择的每页的行数（*）
        clickToSelect: true,                //是否启用点击选中行
        //toolbar: "#tableToolBar",
        //height: getHeight(),
        columns: [{
            width: 38,
            field: 'selected',
            checkbox: true,
        }, {
            title: '行号',
            align: 'center',
            formatter: function (value, row, index) { return index + 1; }
        }, {
            field: 'name',
            title: '名称',
            align: 'center',
            formatter: function (value, row, index) {
                var href = ['<a class="edit btn btn-link" href="/Finance/ItemAttribute/?id=' + row.id + '">',
                value,
                '</a>  ', ]
                return href.join('');// '<button type="button" class="btn btn-link">' + value + '</button>'
            }
        }, {
            field: 'icon',
            title: '图标',
            align: 'center',
            formatter: function (value, row, index) {
                //console.log(typeof (value) + "???");
                if (value == null) {
                    return '';
                }
                return [
                    '<img src="/images/icon/' + value + '" width="36px" height="36px"/>',
                    ' ',
                    '<label >' + value + '</label>'
                ].join('');
            }
        }, {
            field: 'showIndex',
            title: '排序',
            align: 'center',
            events: operateEvents,
            formatter: operateFormatter
        }, {
            field: 'state',
            title: '状态',
            align: 'center',
            events: {
                'click .btn.btn-xs': function (e, value, row, index) {
                    if (isAuthority('293')) {
                        $.ajax({
                            url: "/Item/OpenOrClose",
                            type: "post",
                            dataType: "json",
                            data: { id: row.id },
                            success: function (data) {
                                //Info,Success,Warning,Error
                                var type = data.type;
                                if (type == 1) {
                                    layer.msg(data.content, { icon: 6, time: 2000 },
                                        function () {
                                        });

                                } else {
                                    //layer.msg(data.content, { icon: 5, time: 2000 });
                                }
                                refreshTable();
                            }
                        });
                    }
                },
            },
            formatter: function (value, row, index) {
                var txt = '<button type="button" class="btn btn-xs ' + (value == 0 ? "btn-success" : "btn-primary") + '">' + (value == 0 ? "启用" : "关闭") + '</button>';
                return [txt].join('');
            }
        }, {
            field: 'masterplate',
            title: '模板',
            align: 'center',
            formatter: function (value, row, index) {
                var show =
                ['<button type="button" class="btn btn-xs less" style="width: 32px; margin-bottom: 0px;height: 30px;">-</button>'
                    , '<input type="text" value="' + value + '" class="quantity-count" style="width:48px; height:30px; text-align: center;border: 0;" Disabled>'
                    , '<button type="button" class="btn btn-xs plus" style="width: 32px; margin-bottom: 0px;height: 30px;">+</button>']
                    .join('');
                return '<div>' + show + '</div>';
            },
            events: {

                'click .btn.btn-xs.less': function (e, value, row, index) {
                    if (isAuthority('293')) {
                        $.ajax({
                            url: "/Item/EditMode",
                            type: "post",
                            dataType: "json",
                            data: { id: row.id, op: -1 },
                            success: function (data) {
                                //Info,Success,Warning,Error
                                var type = data.type;
                                if (type == 1) {
                                    layer.msg(data.content, { icon: 6, time: 2000 },
                                        function () {
                                        });

                                } else {
                                    //layer.msg(data.content, { icon: 5, time: 2000 });
                                }
                                refreshTable();
                            }
                        });
                    }
                },
                'click .btn.btn-xs.plus': function (e, value, row, index) {
                    if (isAuthority('293')) {
                        $.ajax({
                            url: "/Item/EditMode",
                            type: "post",
                            dataType: "json",
                            data: { id: row.id, op: 1 },
                            success: function (data) {
                                //Info,Success,Warning,Error
                                var type = data.type;
                                if (type == 1) {
                                    layer.msg(data.content, { icon: 6, time: 2000 },
                                        function () {
                                        });

                                } else {
                                    //layer.msg(data.content, { icon: 5, time: 2000 });
                                }
                                refreshTable();
                            }
                        });
                    }
                }

            }
        }, {
            field: 'showIndex',
            title: '序号',
            align: 'center',
        }, {
            field: 'dataType',
            title: '设置属性',
            align: 'center',
            events: {
                'click .btn.btn-xs': function (e, value, row, index) {
                    //console.log("......");
                    window.location.href = "/Finance/ItemAttribute/Index?id=" + row.id;
                },
            },
            formatter: function (value, row, index) {
                var txt = '<button type="button" class="btn btn-xs btn-primary">属性</button>';
                return [txt].join('');
            }
        }]
    }).on('load-success.bs.table', function (data) {
        //console.log("load success");
    });
}

//自定义的列事件
function operateFormatter(value, row, index) {
    //console.log(index + "===" + ($("table tbody tr").length - 2));
    if (index == 1) {
        var l = ['<a class="edit" href="javascript:void(0)" style="color:gray;" title="上移">',
        ' <i class="glyphicon glyphicon-upload" aria-hidden="true"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="下移">',
        ' <i class="glyphicon glyphicon-download" aria-hidden="true"></i>',
        '</a>'];
        return l.join('');
    } else if (index == ($("table tbody tr").length - 2)) {//最后一行
        //console.log("end");
        var r = ['<a class="edit" href="javascript:void(0)" title="上移">',
        ' <i class="glyphicon glyphicon-upload" aria-hidden="true"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" style="color:gray;" title="下移">',
       ' <i class="glyphicon glyphicon-download" aria-hidden="true"></i>',
       '</a>'];
        return r.join('');
    }
    else return [
        '<a class="edit" href="javascript:void(0)" title="上移">',
        ' <i class="glyphicon glyphicon-upload" aria-hidden="true"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="下移">',
        ' <i class="glyphicon glyphicon-download" aria-hidden="true"></i>',
        '</a>'
    ].join('');
}

window.operateEvents = {
    'click .edit': function (e, value, row, index) {
        if (isAuthority('293')) {
            moveTo2(row.id, -1);
        }

    },
    'click .remove': function (e, value, row, index) {
        if (isAuthority('293')) {
            if (index == $("table tbody tr").length - 2) {
                console.log("end");
            }
            moveTo2(row.id, 1);
        }
    }
};

function moveTo2(key, val) {
    $.ajax({
        url: "/Item/MoveTo",
        type: "post",
        dataType: "json",
        data: { id: key, direction: val },
        success: function (data) {
            //Info,Success,Warning,Error
            var type = data.type;
            if (type == 1) {
                layer.msg(data.content, { icon: 6, time: 2000 },
                    function () {
                        //console.log(222);
                        $tree.jstree(tree)                        //var index = parent.layer.getFrameIndex(window.name);
                        //parent.layer.close(index);
                    });

            } else {
                console.log(66);
                //layer.msg(data.content, { icon: 5, time: 2000 });
            }
            refreshTable();
        }
    });
}
///////////////////////////////////////////////////////////////////////////////
//基础操作
///////////////////////////////////////////////////////////////////////////////

function initTree() {

    $tree.jstree({
        'core': {
            "check_callback": true,
            'data': {
                'type': 'post',
                'url': "/Item/ExcludeStreetAsync",
                'dataType': "json"
            }
            , 'multiple': false
        }
        , "force_text": true
        , "checkbox": {
            "keep_selected_style": false,//是否默认选中
            "three_state": false,//父子级别级联选择
            "tie_selection": false
        },
        "plugins": ["checkbox", "theme", "types"]
    });
    $tree.on('check_node.jstree', function (event, obj) {
        var ref = $tree.jstree(true);
        var nodes = ref.get_checked();  //使用get_checked方法
        //console.log(nodes);
        //console.log(event);

        nodes.sort(function (a, b) {
            return a.length - b.length;
        });

        if (obj.node.id.indexOf('-') <= -1) {
            //console.log(obj.node.id + "???");
            type = obj.node.id;
        } else {
            //console.log(obj.node.id);
            type = obj.node.id.substr(obj.node.id.lastIndexOf('-') + 1);
            //console.log(type);
        }
        $.each(nodes, function (i, nd) {

            if (nd != obj.node.id)
                ref.uncheck_node(nd);
        });


        $table.bootstrapTable('refresh');
    });
}

function multipleCheckedTree() {

    /*
    * 选择父子集的 一起选中
    *
    */
    $tree.jstree({
        'core': {
            "check_callback": true,
            'data': {
                'type': 'post',
                'url': "/Item/ExcludeStreetAsync",
                'dataType': "json"
            }
            //, 'multiple': false
        }
        //, "force_text": true
        , "checkbox": {
            "keep_selected_style": false,//是否默认选中
            //"three_state": false,//父子级别级联选择
            "tie_selection": false
        },
        "plugins": ["checkbox", "theme", "types"]
    });
    var lastNodeSelected = null;
    $tree.on('check_node.jstree', function (event, obj) {
        var ref = $tree.jstree(true);
        var nodes = ref.get_checked();  //使用get_checked方法

        nodes.sort(function (a, b) {
            return a.length - b.length;
        });

        if (lastNodeSelected != null) {
            if (lastNodeSelected.contains(obj.node.id)) {
                console.log(lastNodeSelected.join('|'))
                lastNodeSelected.removeObj(obj.node.id);
                console.log(lastNodeSelected);
            }
            $.each(lastNodeSelected, function (i, nd) {
                console.log("??" + nd);
                if (nd != obj.node.id || obj.node.children.contains(nd)) {
                    ref.uncheck_node(type);
                    lastNodeSelected.removeObj(nd);
                }

            });
        }
        type = nodes[0];// obj.node.id;
        if (obj.node.children.length > 1) {
            lastNodeSelected = [type];
        } else if (obj.node.children.length == 0) {
            ref.uncheck_node(obj.node.id);
            return;
        } else {
            lastNodeSelected = [obj.node.id];
        }
        $table.bootstrapTable('refresh');
    });


    $tree.on('loaded.jstree', function (e, data) {
        var inst = data.instance;
        var item = inst.get_node(e.target.firstChild.firstChild.lastChild);
        console.log(data);
    });

    $tree.on("changed.jstree", function (e, data) {
        console.log(data);
        var selectedArr = [];

    });
}

function MySubmit() {
    RestClick();
    var tab = $('#tb-month').find('.day-td');
    var _arr = [];

    //询问框
    parent.layer.confirm('请确认，是否提交本次排班数据？', {
        btn: ['确定', '取消'], //按钮
        shade: false //不显示遮罩
    }, function (index, layero) {

        parent.layer.close(index);

        $.each(tab, function (ii, val) {
            var _date = $(this).attr("id").substr(3);
            var milliseconds = Date.parse(_date.replace(regEx, "/"));
            var _tdDate = new Date();
            _tdDate.setTime(milliseconds);
            if ($(this).attr("redstate") != undefined && new Date() < _tdDate) {
                var dataIntArr = [];
                dataIntArr = $(this).attr("redstate").split(",").map(function (data) {
                    return +data;
                });
                var arr =
                     {
                         "date": $(this).attr("id").substr(3),
                         "data": $(this).attr("redstate").split(",").map(function (data) {
                             return +data;
                         })
                     };
                _arr.push(arr);
            }
        });
        if (_arr.length <= 0) {
            parent.layer.alert('请选择需要排班的人员')
        } else {
            //console.log(JSON.stringify(_arr));
            $.ajax({
                url: "/Scheduling/InsertPaiBanAsync",
                type: "post",
                dataType: "json",
                data: { strJson: JSON.stringify(_arr) },
                success: function (data) {
                    //Info,Success,Warning,Error
                    var type = data.type;
                    if (type == 1) {
                        layer.msg(data.content,
                            {
                                icon: 6, time: 2000
                            },
                            function () {
                                $("#btn-search").click();

                            });
                    } else {
                        layer.msg(data.content, { icon: 5, time: 2000 });
                        $("#btn-search").click();
                    }
                }
            });
        }
    }, function () {
        return;
    });


}
//获取表格高度
function getHeight() {
    return $(window).height() - 150;
}

//重置表格高度
setTimeout(function () {
    $table.bootstrapTable('resetView');
}, 200);

//重置表格高度
$(window).resize(function () {
    $table.bootstrapTable('resetView', {
        height: getHeight()
    });
});

//刷新表格数据
var refreshTable = function () {
    $table.bootstrapTable('refresh');
    $tree.jstree(true).refresh();
}
//刷新按钮
$('#refreshBtn').click(function (e) {
    $table.bootstrapTable('refresh');
});
////搜索按钮
//$('#searchBtn').click(function (e) {
//    $table.bootstrapTable('refresh');
//});
//插入按钮
$('#insertBtn').click(function (e) {
    //if (type == "" || typeName == "") {
    //    layer.msg("请选择指定区域！", { icon: 5, time: 2000 });
    //    return;
    //}
    parent.layer.open({
        type: 2,
        title: '添加参数',
        shadeClose: false,
        shade: 0.4,
        area: ['680px', '500px'],
        content: '/Finance/Item/Insert?p=' + type,//?type=' + type + "&typeName=" + typeName + "&parentId=" + cityId,
        end: function () {
            refreshTable();
            //$tree.jstree(true).refresh();
        }
    });
});
//编辑按钮
$('#editBtn').click(function (e) {
    var selected = $table.bootstrapTable('getSelections');
    if (selected.length > 1) {
        layer.msg("一次只能修改一条数据！", { icon: 5, time: 2000 });
        return;
    }
    if (selected.length == 0) {
        layer.msg("请选择您要修改的数据！", { icon: 5, time: 2000 });
        return;
    }

    var allData = [];
    $.each($table.bootstrapTable('getData'), function (i, val) {
        allData.push({ idx: i, data: val });
    });
    var ttids = $.Enumerable.From(allData)
        .Where(function (x) { return x.data.id == selected[0].id; })
        .Select(function (x) { return { idx: x.idx, id: x.data.id }; })
        .First();

    console.log(ttids.idx + "----" + ttids.id);
    editData(selected[0].id, ttids.idx);
});
function editCallback(id, idx) {
    //EditModel
    $.ajax({
        url: "/Finance/Item/EditModel",
        type: "post",
        dataType: "json",
        data: { id: id },
        success: function (data) {
            //Info,Success,Warning,Error
            var type = data.type;
            if (type == 1) {
                $table.bootstrapTable('updateRow', { index: idx, row: data.data });
            } else {
                layer.msg(data.content, { icon: 5, time: 2000 });
            }
        }
    });
}
//打开编辑窗口
function editData(id, idx) {
    parent.layer.open({
        type: 2,
        title: '修改参数',
        shadeClose: false,
        shade: 0.4,
        area: ['680px', '500px'],
        content: '/Finance/Item/Edit?id=' + id,
        end: function () {
            //EditModel
            editCallback(id, idx);            
            //refreshTable();
        }
    });
}
//删除按钮
$('#deleteBtn').click(function (e) {
    var selected = $table.bootstrapTable('getSelections');
    if (selected.length == 0) {
        layer.msg("请选择您要删除的数据！", { icon: 5, time: 2000 });
        return;
    }
    var arr = [];
    for (var i = 0; i < selected.length; i++) {
        arr.push(selected[i].id);
    }
    var ids = arr.join(",");
    layer.confirm('您确定要删除所选数据吗', {
        btn: ['是的', '取消'] //按钮
    }, function () {
        $.ajax({
            url: "/Finance/Item/DeleteAsync",
            type: "post",
            dataType: "json",
            data: { ids: ids },
            success: function (data) {
                //Info,Success,Warning,Error
                var type = data.type;
                if (type == 1) {
                    layer.msg(data.content,
                        {
                            icon: 6, time: 2000
                        },
                        function () {
                            refreshTable();
                            //$tree.jstree(true).refresh();
                        });
                } else {
                    layer.msg(data.content, { icon: 5, time: 2000 });
                }
            }
        });
    }, function () {
        return;
    });
});

Array.prototype.contains = function (needle) {
    for (i in this) {
        if (this[i] == needle) return true;
    }
    return false;
}
/*
　 *　方法:Array.remove(dx)
　 *　功能:删除数组元素.
　 *　参数:dx删除元素的下标.
　 *　返回:在原数组上修改数组
*/
//经常用的是通过遍历,重构数组.
Array.prototype.remove = function (dx) {
    if (isNaN(dx) || dx > this.length) { return false; }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i]
        }
    }
    this.length -= 1
}
/*
　 *　方法:Array.baoremove(dx)
　 *　功能:删除数组元素.
　 *　参数:dx删除元素的下标.
　 *　返回:在原数组上修改数组.
　 */
//也可以用splice来实现.
Array.prototype.baoremove = function (dx) { // www.jb51.net
    if (isNaN(dx) || dx > this.length) { return false; }
    this.splice(dx, 1);
}

Array.prototype.removeObj = function (obj) {//按序列移除
    for (var i = 0; i < this.length; ++i) {
        if (this[i] == obj) {
            if (i > this.length / 2) {
                for (var j = i; j < this.length - 1; ++j) {
                    this[j] = this[j + 1];
                }
                this.pop();
            }
            else {
                for (var j = i; j > 0; --j) {
                    this[j] = this[j - 1];
                }
                this.shift();
            }
            break;
        }
    }
};
/** 
*js中更改日期  
* y年， m月， d日， h小时， n分钟，s秒  
*/
Date.prototype.add = function (part, value) {
    value *= 1;
    if (isNaN(value)) {
        value = 0;
    }
    switch (part) {
        case "y":
            this.setFullYear(this.getFullYear() + value);
            break;
        case "m":
            this.setMonth(this.getMonth() + value);
            break;
        case "d":
            this.setDate(this.getDate() + value);
            break;
        case "h":
            this.setHours(this.getHours() + value);
            break;
        case "n":
            this.setMinutes(this.getMinutes() + value);
            break;
        case "s":
            this.setSeconds(this.getSeconds() + value);
            break;
        default:

    }
}
/**       
 * 对Date的扩展，将 Date 转化为指定格式的String       
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符       
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)       
 * eg:       
 * (new Date()).pattern("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423       
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04       
 * (new Date()).pattern("yyyy-MM-dd EE HH:mm:ss") ==> 2009-03-10 周二 08:09:04       
 * (new Date()).pattern("yyyy-MM-dd EEE HH:mm:ss") ==> 2009-03-10 星期二 08:09:04       
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18       
 */
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份           
        "d+": this.getDate(), //日           
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
        "H+": this.getHours(), //小时           
        "m+": this.getMinutes(), //分           
        "s+": this.getSeconds(), //秒           
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
        "S": this.getMilliseconds() //毫秒           
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
